#
#This script scan all the code, and try to recongize the arch code part code
#
import sys
import os

class CFileParse():
    def __init__(self,file_name):
        self.file_name=file_name
        self.content=[]
        self.line_number=0
        
        try:
            with open(self.file_name) as f:
                self.content=f.readlines()
        except Exception,e:
            if os.path.islink(self.file_name):
                pass
            else:
                print(Exception,":",e)
        
        self.multi_comment_flag=False
        self.point_str = ["ARM","MIPS","X86"]
        self.point = [0,0,0]
        self.point_line = []

    def parse_comment(self,origin_line):
        line=origin_line
        begin=-1
        end=-1
        if not self.multi_comment_flag:
            begin=line.find("/*")
            if begin >= 0:
                self.multi_comment_flag=True
                
        if self.multi_comment_flag:
            end=line.find("*/")
            if end >= 0:
                self.multi_comment_flag=False
                
        if begin >= 0 and end >=0:
            line=origin_line[:begin]+origin_line[end+2:]
        elif begin >=0:
            if begin == 0:
                line=""
            else:
                line=origin_line[:begin]
        elif end >= 0:
            line=origin_line[end+2:]
        else:
            if self.multi_comment_flag:
                line=""
            pos=line.find("//") #one_line_comment
            if pos >= 0:
                line=origin_line[:pos]

        #print(begin,end,self.multi_comment_flag,line)
        line=line.strip()        
        #print(line,)
        
        return line
    
    def parse_macro(self,line):
        #it didn't contain # or it was include line
        if not line.startswith('#') or line.split()[0] in ["#include"]:
            return line
        #print(line)

        if line.split()[0] in ['#if','#ifdef','#ifndef','#elif']:
            upper_line=line.upper()
            arm_keys=["AARCH","ARM"]
            mips_keys=["MIPS"]
            x86_keys=["X86"]
            found_flag=False
            
            for find_str in arm_keys:
                if upper_line.find(find_str) > 0:
                    self.point[0]=1
                    found_flag=True
            for find_str in mips_keys:
                if upper_line.find(find_str) > 0:
                    self.point[1]=1
                    found_flag=True
            for find_str in x86_keys:
                if upper_line.find(find_str) > 0:
                    self.point[2]=1
                    found_flag=True
            if found_flag:
                self.point_line.append(self.line_number)
            
            
        return line
    
    def parse(self):
        func_list=[]
        func_list.append(self.parse_comment)
        func_list.append(self.parse_macro)
        
        line=""
        for origin_line in self.content:
            tmp_line=origin_line.strip()
            self.line_number+=1
            
            line +=tmp_line
            if tmp_line.endswith('\\'):                
                continue           

            for func in func_list:
                line=func(line)
            line=""
                
    def print_result(self):
        global global_files_count
        if sum(self.point)>1:
            global_files_count+=1
            arch_tag="|".join([ self.point_str[i] for i in range(3) if self.point[i] > 0 ])
            match_score=len(self.point_line)
            
            
            print("i=%-4d %-13s %2d %s" %(global_files_count,arch_tag,match_score,self.file_name))

class CFolderParse():
    def __init__(self,dir):
        self.dir=dir
    
    def parse(self):
        print("handle folder %s..." %(self.dir))
        handled_files=0
        for root, dirs, files in os.walk(self.dir):
            for name in files:
                if name.split(".") > 1 and name.split(".")[-1] in ["h","cc","hpp","c","cpp","hh"]:
                    obj=CFileParse(os.path.join(root, name))
                    obj.parse()
                    handled_files+=1
                    obj.print_result()
        print("handle folder %s done, total handles files:%d" %(self.dir,handled_files))

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print("Please specify the file or directory path.")
        sys.exit(0)
    
    global_files_count=0
    for path in sys.argv[1:]:
        if not os.path.exists(path):
            print("The given path[%s] was not existed." %(path))
            continue
        if os.path.isdir(path):
            cFolderParse = CFolderParse(path)
            cFolderParse.parse()
        elif os.path.isfile(path):
            fileParse = CFileParse(path)
            fileParse.parse()
            fileParse.print_result()
  
    
    
    
    
    
    
    
    
    